package com.cjh.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    //有效期
    private static final long TIME=1000*60*60*24;
    //签名
    private static final String SIGNATURE="admin";

    public static String createToken(String username){
        JwtBuilder jwtBuilder = Jwts.builder();
        String token=jwtBuilder
                //设置header（头部）
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //设置payload（有效载荷）
                .claim("username",username)
                .setSubject("hello jwt")
                .setExpiration(new Date(System.currentTimeMillis()+TIME))
                .setId(UUID.randomUUID().toString())
                //设置signature（签名）
                .signWith(SignatureAlgorithm.HS256,SIGNATURE)
                .compact();
        return token;
    }

    public static boolean checkToken(String token){
        JwtParser jwtParser = Jwts.parser();
        try {
            Jws<Claims> claimsJws = jwtParser.setSigningKey(SIGNATURE).parseClaimsJws(token);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
